package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	go_logger "github.com/phachon/go-logger"
	"net/http"
	"strings"
	"waimai/controller"
	"waimai/tool"
)

func main(){
	logger := go_logger.NewLogger()
	cfg,err:=tool.ParseConfig("./config/app.json")
	if err!=nil {
		logger.Error(err.Error())
		return
	}
	//数据库连接
	_,err = tool.OrmEngine(cfg)
	fmt.Println(tool.DbEngine)
	if err!=nil {
		logger.Error(err.Error())
		return
	}
	app :=gin.Default()

	//redis初始化
	tool.InitRedisStore()

	//启用中间件
	app.Use(Cors())

	registerRouter(app)


	app.Run(cfg.AppHost+":"+cfg.AppPort)

}

func registerRouter(router *gin.Engine){
	new(controller.HelloController).Router(router)
	new(controller.MemberController).Router(router)
}


//跨域访问中间件
func Cors()gin.HandlerFunc{
	return func(c *gin.Context){
		method:=c.Request.Method
		origin:=c.Request.Header.Get("Origin")
		var headerKeys []string
		for key,_:=range c.Request.Header{
			headerKeys=append(headerKeys,key)
		}
		headerStr:=strings.Join(headerKeys,",")
		if headerStr !=""{
			headerStr=fmt.Sprintf("access-control-allow-origin,access-control-allow-headers,%s",headerStr)
		}else{
			headerStr="access-control-allow-origin,access-control-allow-headers"
		}

		if origin !=""{
			c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Origin", "*") // 设置允许访问所有域
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
			c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma,token,openid,opentoken")
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")
			c.Header("Access-Control-Max-Age", "172800")
			c.Header("Access-Control-Allow-Credentials", "false")
		}
		if method=="OPTIONS"{
			c.JSON(http.StatusOK,"Options Request")
		}
		c.Next()
	}
}